package com.edu.fafu.studentrepair.fragments;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.icu.text.RelativeDateTimeFormatter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.edu.fafu.studentrepair.MainActivity;
import com.edu.fafu.studentrepair.R;
import com.edu.fafu.studentrepair.adapter.Record_Adapter;
import com.edu.fafu.studentrepair.command.Dictionary;
import com.edu.fafu.studentrepair.command.LocalDataStream;
import com.edu.fafu.studentrepair.command.ReJsonRsp;
import com.edu.fafu.studentrepair.entitys.AppPojo4list;
import com.edu.fafu.studentrepair.entitys.RecordList;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class RecordFragment extends Fragment {
    private static int RENDER = 1;
    private RecyclerView recyclerView;
    private ProgressDialog pd;
    private String name;
    private String type;
    private List<RecordList> recordLists;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RENDER) {
                dataRender();
            } }
    };
    @SuppressLint("ValidFragment")
    public RecordFragment(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("recordFragment", "onStart: ");
        //刚创建的时候，刷新数据
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden)  return;//隐藏页面，不操作
        initRecordList();
    }

    private void dataRender() {
        Record_Adapter adapter = new Record_Adapter(recordLists,new Record_Adapter.OnItemClickListener(){
            @Override
            public void onItemClick(View view, Integer id) {
                MainActivity mainActivity = (MainActivity) getActivity();
                int oLast = mainActivity.getLastfragment();
                mainActivity.setRecordId(id);
                mainActivity.setLastfragment(Dictionary.Page.FRAGMENT_RECORD_ITEM);
                mainActivity.switchFragment(oLast,Dictionary.Page.FRAGMENT_RECORD_ITEM);
            }
        },getActivity());
        recyclerView.setAdapter(adapter);
        recyclerView.getAdapter().notifyDataSetChanged();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View view = inflater.inflate(R.layout.record_list_main, container, false);
        recyclerView = view.findViewById(R.id.recordList_recycler);
        LinearLayoutManager manager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(manager);
        initRecordList();

        return view;
    }
    private List<RecordList>  initRecordList(ReJsonRsp reJsonRsp) {
        JSONArray  appPojo4lists = (JSONArray) reJsonRsp.getData();
        Log.i("dataRender", "initRecordList: "+appPojo4lists);
        Log.i("dataRender", "initRecordList: "+appPojo4lists);
        List<RecordList> recordLists = new ArrayList<>();
        RecordList recordList;
        for(int i = 0;i<appPojo4lists.size();i++){
            JSONObject data = appPojo4lists.getJSONObject(i);
            recordList = new RecordList();
            recordList.setId((Integer) data.get("id"));
            recordList.setStudentName((String) data.get("name"));
            recordList.setStudentAddr((String) data.get("studentAddr"));
            recordList.setAddTime((Long) data.get("addTime"));
            recordList.setMsg((String) data.get("msg"));
            recordList.setState((String)data.get("stateStr"));
            recordList.setPic((String)data.get("pic"));
            recordLists.add(recordList);
        }
        return recordLists;
    }
    private void initRecordList(){
        String idenAndpwd = "";
        recordLists = new ArrayList<>();
        try {//判断是否已经登陆
            idenAndpwd = LocalDataStream.read(getActivity().openFileInput("data"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(idenAndpwd.equals("")){
            Toast toast = Toast.makeText(getActivity(),"非法使用",Toast.LENGTH_LONG);
            toast.show();
            return ;
        }
        /**
         * 开始从后端取值
         */
        String iden = idenAndpwd.split("_")[0];
        OkHttpClient okHttpClient = new OkHttpClient();
        Log.i(name+"Record", "initRecordList: "+Dictionary.url.head+"/app/search?id="+iden+"&type="+type);
        final Request request = new Request.Builder()
                .url(Dictionary.url.head+"app/search?id="+iden+"&type="+type)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        pd= ProgressDialog.show(getActivity(), "获取信息", "获取信息中…");
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(name+"Record", "onFailure: "+e);
                pd.dismiss();
                Toast toast = Toast.makeText(getActivity(),"数据请求异常",Toast.LENGTH_LONG);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.i(name+"Record", "onResponse: " + json);
                ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                recordLists =  initRecordList(reJsonRsp);//渲染list
                Message message = new Message();
                message.what=RENDER;
                handler.sendMessage(message);
                pd.dismiss();
            }
        });
        Log.i("redenData", "initRecordList: "+recordLists.toString());
    }


}
